import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { IResponse } from 'src/interfaces/response.interface';
import { User, UserDocument } from 'src/schemas/user.schema';
import { to } from 'src/utils/to';

const logger = new Logger('user.service');
@Injectable()
export class UserService {
  private response: IResponse;
  constructor(@InjectModel('User') private userModel: Model<UserDocument>) {}

  /**
   * @description 注册方法
   * @author maya
   * @date 2021-10-04
   * @param {User} user
   * @returns {*}
   */
  async create(user: User) {
    let [err, data] = await to(this.findOneByPhone(user.phone));
    if (err) {
      logger.error(`发生了一些错误${err}`);
      this.response = {
        code: 2,
        msg: `用户注册失败！请联系相关负责人，错误详情：${err}`,
      };
    } else if (data) {
      this.response = { code: 1, msg: '当前手机号已经注册！' };
      logger.log(this.response.msg);
    } else {
      try {
        const createUser = new this.userModel(user);
        createUser.save();
        this.response = { code: 0, msg: '用户注册成功' };
      } catch (error) {
        this.response = {
          code: 2,
          msg: `用户注册失败！请联系相关负责人，错误详情：${error}`,
        };
        logger.error(this.response.msg);
        throw this.response;
      }
    }
    return this.response;
  }

  /**
   * @description 通过手机号查找用户
   * @date 2021-10-04
   * @param {string} phone
   * @returns {*}
   */
  findOneByPhone(phone: string) {
    return this.userModel.findOne({
      phone: phone,
    });
  }

  findAll() {
    return `This action returns all user`;
  }

  update(id: number, updateUserDto: User) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
